<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/11/23
 * Time: 10:53 AM
 */

namespace app\shop\controller;

use app\shop\model\Category as CategoryModel;
use think\db\Query;
use think\Exception;
use think\Loader;
use think\Request;


class Category extends \ShopController
{

    static private $DiDuiCategory = [];

    /**
     * @OA\Get( tags={"Category"}, path="/shop/category/all", summary="获取所有商品分类", description="获取所有商品分类",
     *   @OA\Response( response="200", description="请求成功",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/Category") )
     *   )
     * )
     */
    public function all()
    {
        try {
            $this->successTerminate($this->_all());
        } catch(Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
        return null;
    }

    protected function _all($flush = false)
    {
        return $this->cacheFirst(\CacheKey::CATEGORY_ALL, function() {
            $all = CategoryModel::all(function ($query) {
                /* @var $query Query */
                $query
                    ->field('cate_id, cate_name, parent_id')
                    ->where('is_show', 1)
                    ->order('sort_order');
            });
            return $this->tree($all, 0);
        }, $flush);
    }

    /**
     * 允许限制级数
     * @param $categories
     * @param int $pid
     * @param int $levelLimit
     * @param int $level
     * @return array
     */
    private function tree($categories, $pid = 0, $levelLimit = 0, $level = 1)
    {
        $children = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] === $pid) {

                if ($levelLimit === 0 || $level < $levelLimit) {
                    $category['children'] = $this->tree($categories, $category['cate_id'], $levelLimit, $level + 1);
                }

                $children[] = $category;
            }
        }
        return $children;
    }

    /**
     * 添加分类
     * @OA\Post( tags={"Category"}, path="/shop/category/add", summary="添加商品分类",
     *   @OA\Response( response="200", description="请求成功，返回商品全部分类信息",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/Category") ),
     *   ),
     *   @OA\RequestBody( required=true,
     *     @OA\MediaType( mediaType="application/x-www-form-urlencoded",
     *       @OA\Schema( type="object", required={"cateName", "parentId"},
     *         @OA\Property( property="cateName", description="商品分类名称", type="string", example="测试分类", ),
     *         @OA\Property( property="parentId", description="父级分类ID", type="integer", example=0, ),
     *         @OA\Property( property="inUse", description="是否启用", type="boolean", ),
     *       ),
     *     ),
     *   ),
     * )
     */
    public function save(Request $request)
    {
        $data = $request->post();
        /* @var $validate \ShopValidate */
        $validate = Loader::validate('Category');
        if ( !$validate->scene('save')->check($data) ) {
            return $validate->getError();
        }

        try {
            (new CategoryModel($data))->save();

            $this->successTerminate($this->_all(true));
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    public function test()
    {

        $validate = Loader::validate('Category');
        $data = ['parent_id' => 100];
        if (!$validate->scene('add')->check($data)) {
            return $validate->getError();
        }
    }

    /**
     * 检测分类ID是否存在
     * @param $cateId
     */
    public function checkExists($cateId)
    {
        return $cateId == 0 || ! is_null( CategoryModel::get($cateId) );
    }

    protected function postMethods()
    {
        return [
            'save',
        ];
    }

    /**
     * 查询分类下所有子分类 返回该分类下所有分类
     */
    public function getCategoryAffiliate($cate_id,$sqlData=false){

        $CategoryModel = new CategoryModel();
        $CategoryDb = $CategoryModel->CategoryDb();
        $CategoryData = $CategoryDb->where('is_show',1)->select();
        foreach ($CategoryData as $CategoryK=>$CategoryV){
            if($cate_id==$CategoryV['cate_id']){
                static::$DiDuiCategory[] = $CategoryV;
            }
        }
        $this->DiGuiCategory($CategoryData,$cate_id);
        if ($sqlData){
            $retData = [];
            $sqlS = static::$DiDuiCategory;
            foreach ($sqlS as $v){
                $retData[] =  $v['cate_id'];
            }

            return $retData;
        }
        return static::$DiDuiCategory;

    }
    //递归分类
    private function DiGuiCategory($CategoryData,$cate_id){
        foreach ($CategoryData as $CategoryK=>$CategoryV){
            if($cate_id==$CategoryV['parent_id']){
                static::$DiDuiCategory[] = $CategoryV;
                $this->DiGuiCategory($CategoryData,$CategoryV['cate_id']);
            }
        }
    }

    public function getChildCategory($cate_id){
        try {
            $CategoryModel = new CategoryModel();
            $CategoryDb = $CategoryModel->CategoryDb();
    
            $data =  $CategoryModel->where('parent_id',$cate_id)->field('cate_id,cate_name')->select();

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

}